package com.smartcruise.util.network;

import android.util.Log;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.google.gson.Gson;
import com.smartcruise.data.cruiseData.CruiseContract;
import com.smartcruise.data.cruiseData.CruiseData;
import com.smartcruise.data.cruiseData.NodeTaskListBean;
import com.smartcruise.service.UpLoadLocationManager;
import com.smartcruise.util.FileUtils;
import com.smartcruise.util.ListUtils;
import com.smartcruise.util.image.ImageUtils;
import com.smartcruise.util.network.callBack.BaseCallBack;
import com.smartcruise.util.network.callBack.UploadFileCallBack;
import com.smartcruise.util.network.customerObserver.SimpleBackObserver;
import com.smartcruise.util.network.netUtils.NetCollection;
import com.smartcruise.util.network.netUtils.Result;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.realm.Realm;

/**
 * Created by FengChaoQun
 * on 2018/3/2 0002
 * 上传节点数据 不显示进度框
 */

public class NodeUploadBack {

    private final int NODE_SIMPLE_UPLOAD = 1;//单节点部分上传
    private final int NODE_ALL_UPLOAD = 2;//单节点全部上传

    private CruiseData cruiseData;
    private Realm realm;
    private BaseCallBack baseCallBack;
    private int uploadType; //1:单节点部分上传  2:单节点全部上传  3:整体部分上传  4:整体全部上传
    private NodeTaskListBean nodeTaskListBean;//
    private boolean needUploadTask = true;//标记是否需要上传任务数据 防止在上传全部节点的时候 多次上传任务数据

    public NodeUploadBack(CruiseData cruiseData, Realm realm, NodeTaskListBean nodeTaskListBean) {
        this.cruiseData = cruiseData;
        this.realm = realm;
        this.nodeTaskListBean = nodeTaskListBean;
    }

    /**
     * description:上传一个节点的简略信息
     */

    public void uploadOneNodeSimpleData(final BaseCallBack baseCallBack) {

        this.baseCallBack = baseCallBack;
        uploadType = NODE_SIMPLE_UPLOAD;

        //先上传节点任务图片和视频
        List<String> imageList = nodeTaskListBean.getOriginalImage();
        List<String> videoList = nodeTaskListBean.getOriginalVideos();
        final List<String> audioList = nodeTaskListBean.getOriginalAudios();

        //先压缩文件 再上传文件 最后上传到服务器
        uploadFile(imageList, videoList, audioList, new BaseCallBack() {
            @Override
            public void onSuccess(Result result) {
                realm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {//整理数据
                        nodeTaskListBean.buildTaskSimpleData(cruiseData);
                        Log.d("NodeTaskDataEditPresent", "" + nodeTaskListBean.getTaskResultMap());
                    }
                });
                uploadTaskData();
            }

            @Override
            public void onFail(Result result) {
                baseCallBack.onFail(result);
            }

            @Override
            public void onError(Throwable e) {
                baseCallBack.onError(e);
            }
        });

    }

    /**
     * description:上传一个节点的全部信息
     * 1.先上传缩略图信息
     * 2.再上传原图信息
     * 3.整体数据上传
     */

    public void uploadOneNodeAllData(final BaseCallBack baseCallBack) {

        this.baseCallBack = baseCallBack;
        uploadType = NODE_ALL_UPLOAD;

        //先上传节点任务图片和视频
        final List<String> imageList = nodeTaskListBean.getOriginalImage();
        final List<String> videoList = nodeTaskListBean.getOriginalVideos();
        final List<String> audioList = nodeTaskListBean.getOriginalAudios();


        //1.上传缩略图
        uploadFile(imageList, videoList, audioList, new BaseCallBack() {
            @Override
            public void onSuccess(Result result) {
                realm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {//整理数据
                        nodeTaskListBean.buildTaskSimpleData(cruiseData);
                        Log.d("NodeTaskDataEditPresent", "" + nodeTaskListBean.getTaskResultMap());
                    }
                });

                Map<String, String> map = new HashMap<>();
                if (ListUtils.isHaveContent(imageList)) {
                    for (String s : imageList) {
                        map.put(FileUtils.getFileSimpleName(s), s);
                    }
                }
                if (ListUtils.isHaveContent(videoList)) {
                    for (String s : videoList) {
                        map.put(FileUtils.getFileSimpleName(s), s);
                    }
                }
                if (ListUtils.isHaveContent(audioList)) {
                    for (String s : audioList) {
                        map.put(FileUtils.getFileSimpleName(s), s);
                    }
                }

                //2.然后上传原图
                uploadFile(map, new BaseCallBack() {
                    @Override
                    public void onSuccess(Result result) {
                        realm.executeTransaction(new Realm.Transaction() {
                            @Override
                            public void execute(Realm realm) {//整理数据
                                nodeTaskListBean.buildTaskAllData(cruiseData);
                                Log.d("NodeTaskDataEditPresent", "" + nodeTaskListBean.getTaskResultMap());
                            }
                        });
                        //3.最后上传整体数据
                        uploadTaskData();
                    }

                    @Override
                    public void onFail(Result result) {
                        baseCallBack.onFail(result);
                    }

                    @Override
                    public void onError(Throwable e) {
                        baseCallBack.onError(e);
                    }
                });
            }

            @Override
            public void onFail(Result result) {
                baseCallBack.onFail(result);
            }

            @Override
            public void onError(Throwable e) {
                baseCallBack.onError(e);
            }
        });
    }

    /**
     * description:先压缩 再上传文件
     */

    private void uploadFile(List<String> imageList, List<String> videoList, final List<String> audioList, final BaseCallBack baseCallBack) {
        ImageUtils.getCompressedData(imageList, videoList, new Observer<Map<String, String>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
            }

            @Override
            public void onNext(Map<String, String> stringStringMap) {
                Log.d("ReportDataPresenterImp", "stringStringMap:" + stringStringMap);
                if (stringStringMap == null || stringStringMap.isEmpty()) {//没有图片和视频数据
                    stringStringMap = new HashMap<>();
                }
                if (audioList != null && !audioList.isEmpty()) {//添加语音数据
                    for (String s : audioList) {
                        stringStringMap.put(FileUtils.getFileSimpleName(s), s);
                    }
                }
                uploadFile(stringStringMap, baseCallBack);
            }

            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
                baseCallBack.onError(throwable);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * description:上传文件
     */

    private void uploadFile(Map<String, String> data, final BaseCallBack baseCallBack) {

        if (data == null || data.isEmpty()) {//没有需要上传的数据
            baseCallBack.onSuccess(null);
            return;
        }

        FileUpload fileUpload = new FileUpload(data, new UploadFileCallBack() {
            @Override
            public void onStart() {
            }

            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

            }

            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                baseCallBack.onSuccess(null);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                if (clientExcepion != null) {
                    clientExcepion.printStackTrace();
                    baseCallBack.onError(clientExcepion);
                }
                if (serviceException != null) {
                    serviceException.printStackTrace();
                    baseCallBack.onError(serviceException);
                }
            }
        });
        fileUpload.start();
    }

    /**
     * description:上传数据包
     */

    private void uploadTaskData() {
        if (!needUploadTask) {
            baseCallBack.onSuccess(null);
            return;
        }

        if (CruiseContract.TASK_IS_END.equals(cruiseData.getStatusInApp())) {//上传已经完成的任务之前 先上传坐标数据
            UpLoadLocationManager.getInstance().upLoadLocalData(new BaseCallBack() {
                @Override
                public void onSuccess(Result result) {
                    final CruiseData copyDate = realm.copyFromRealm(cruiseData);
                    copyDate.backUpId();
                    Gson gson = new Gson();

                    NetCollection.pushTask2(gson.toJson(copyDate), new SimpleBackObserver(new BaseCallBack() {
                        @Override
                        public void onSuccess(final Result result) {
                            realm.executeTransaction(new Realm.Transaction() {
                                @Override
                                public void execute(Realm realm) {

                                    //上传成功后 更新服务器id
                                    String serverId = result.getData();
                                    cruiseData.setServerId(serverId);

                                    //更新数据上传状态
                                    switch (uploadType) {
                                        case NODE_SIMPLE_UPLOAD:
                                            nodeTaskListBean.setUploadStatus(1);
                                            cruiseData.buildUploadType();
                                            break;
                                        case NODE_ALL_UPLOAD:
                                            nodeTaskListBean.setUploadStatus(2);
                                            cruiseData.buildUploadType();
                                            break;
                                    }

                                    //如果是网络数据 将本地图片清空
                                    if (cruiseData.isFromNet()) {
                                        nodeTaskListBean.clearOriginalFiles();
                                    }
                                }
                            });
                            baseCallBack.onSuccess(result);
                        }

                        @Override
                        public void onFail(Result result) {
                            baseCallBack.onFail(result);
                        }

                        @Override
                        public void onError(Throwable e) {
                            baseCallBack.onError(e);
                        }
                    }));
                }

                @Override
                public void onFail(Result result) {
                    baseCallBack.onFail(result);
                }

                @Override
                public void onError(Throwable e) {
                    baseCallBack.onError(e);
                }
            });
        }
    }

    public void setNeedUploadTask(boolean needUploadTask) {
        this.needUploadTask = needUploadTask;
    }
}
